<cfparam name="resetFilters" default="false">

<cfoutput>

	<cfscript>
		isFiltered = false;
		queryParams = StructNew();
		// Base
		base = new assets.calgrants.com.Base();
		pbsScholarshipTypes = base.getPBSScholarshipTypes();
		nonPBSScholarshipTypes = base.getNonPBSScholarshipTypes();
		// Stored Procedure
		storedProcedureGateway = new assets.calgrants.com.gateway.StoredProcedureGateway();
		regions = storedProcedureGateway.call("getDistinctRegions");
		cohorts = storedProcedureGateway.call("getDistinctCohorts");
		lastCohort = ListLast(ValueList(cohorts.Cohort));
		scholarshipTypes = storedProcedureGateway.call("getDistinctScholarshipTypes");
	</cfscript>
	<!--- <cfif NOT IsDefined("client.scholarships.orderBy") or resetFilters>
		<cfset client.scholarships.orderBy = "Last_Name">
	<cfelseif IsDefined("orderBy")>
		<cfset client.scholarships.orderBy = orderBy>
	</cfif>
	<cfif NOT IsDefined("client.scholarships.orderDir") or resetFilters>
		<cfset client.scholarships.orderDir = "asc">
	<cfelseif IsDefined("orderDir")>
		<cfset client.scholarships.orderDir = orderDir>
	</cfif> --->
	<cfif NOT IsDefined("client.scholarships.cohort") or resetFilters>
		<cfset client.scholarships.cohort = lastCohort>
	<cfelseif IsDefined("filterCohort")>
		<cfset client.scholarships.cohort = filterCohort>
	</cfif>
	<cfif client.scholarships.cohort neq lastCohort>
		<cfset isFiltered = true />
		<cfset queryParams.Cohort = client.scholarships.cohort />
	<cfelse>
		<cfset queryParams.Cohort = lastCohort />
	</cfif>
	
	<cfset filterScholarshipType = "All" />
	<cfif NOT IsDefined("client.scholarships.scholarshipType") or resetFilters>
		<cfset client.scholarships.scholarshipType = "All">
	<cfelseif IsDefined("filterScholarshipType")>
		<cfset client.scholarships.scholarshipType = filterScholarshipType>
	</cfif>
	<cfif client.scholarships.scholarshipType neq "All">
		<cfset isFiltered = true />
		<cfset queryParams.Scholarship_Type = client.scholarships.scholarshipType />
	</cfif>
	
	<cfif NOT IsDefined("client.scholarships.scholarshipTypes") or resetFilters>
		<cfset client.scholarships.scholarshipTypes = "All">
	<cfelseif IsDefined("filterScholarshipTypes")>
		<cfset client.scholarships.scholarshipTypes = filterScholarshipTypes>
	</cfif>
	<cfif client.scholarships.scholarshipTypes neq "All">
		<cfset isFiltered = true />
		<cfif client.scholarships.scholarshipTypes eq "PBS">
			<cfset queryParams.scholarshipTypes = pbsScholarshipTypes>
		<cfelseif client.scholarships.scholarshipTypes eq "Non-PBS">
			<cfset queryParams.scholarshipTypes = nonPBSScholarshipTypes>
		<cfelse>
			<cfset queryParams.scholarshipTypes = client.scholarships.scholarshipTypes />
		</cfif>
	</cfif>
	
	<cfif NOT IsDefined("client.scholarships.organizationIDs") or resetFilters>
		<cfset client.scholarships.organizationIDs = "All">
	<cfelseif IsDefined("filterOrganizationIDs")>
		<cfset client.scholarships.organizationIDs = filterOrganizationIDs>
	</cfif>
	<cfif client.scholarships.organizationIDs neq "All">
		<cfset isFiltered = true />
		<cfset queryParams.organizationIDs = client.scholarships.organizationIDs />
	</cfif>
	
	<cfif IsUserInRole("Super User") or GetAuthUser() eq 620>
		<cfif NOT IsDefined("client.scholarships.regionIDs") or resetFilters>
			<cfset client.scholarships.regionIDs = "All">
		<cfelseif IsDefined("filterRegionIDs")>
			<cfset client.scholarships.regionIDs = filterRegionIDs>
		</cfif>
	<cfelseif IsUserInRole("Regional Admin")>
		<cfset client.scholarships.regionIDs = request.authUser.regionID>
	</cfif>
	<cfif client.scholarships.regionIDs neq "All">
		<cfset isFiltered = true />
		<cfset queryParams.regionIDs = client.scholarships.regionIDs />
	</cfif>
	<!--- override Claimed filter --->
	<cfset filterClaimed = "All"/>
	<cfif NOT IsDefined("client.scholarships.claimed") or resetFilters>
		<cfset client.scholarships.claimed = "All">
	<cfelseif IsDefined("filterClaimed")>
		<cfset client.scholarships.claimed = filterClaimed>
	</cfif>
	<cfif client.scholarships.claimed neq "All">
		<cfset isFiltered = true />
		<cfset queryParams.claimed = client.scholarships.claimed />
	</cfif>
	
	<cfif NOT IsDefined("client.scholarships.claimStatus") or resetFilters>
		<cfset client.scholarships.claimStatus = "All">
	<cfelseif IsDefined("filterClaimStatus")>
		<cfset client.scholarships.claimStatus = filterClaimStatus>
	</cfif>
	<cfif client.scholarships.claimStatus neq "All">
		<cfset isFiltered = true />
		<cfset queryParams.claimStatus = client.scholarships.claimStatus />
	</cfif>
	
	<cfwddx action="cfml2wddx" input="#queryParams#" output="client.scholarships.queryParamsWDDX" />
	
	<cfscript>
		scholarshipGateway = new assets.calgrants.com.gateway.ScholarshipGateway();
		scholarships = scholarshipGateway.query(argumentCollection = queryParams);
		organizationGateway = new assets.calgrants.com.gateway.OrganizationGateway();
		organizations = organizationGateway.query(regionIDs = IIf(IsUserInRole("Regional Admin"), request.authUser.regionID, ""), Organization_ID = IIf(IsUserInRole("Organizer") OR IsUserInRole("Site Contact"), request.authUser.organizationID, ""));
	</cfscript>
	
	<h3>Scholarships<cfif isFiltered> <small><em>filtered</em></small></cfif></h3>

	<div class="row-fluid" style="margin-bottom: 10px;">
		<div class="span12">
			<a id="filterLink" href="##" class="btn" onclick="toggleFilter('filter')">Show filters</a>
			<div class="btn-group">
				<button class="btn dropdown-toggle" data-toggle="dropdown">Actions</button>
				<button class="btn dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
				<ul class="dropdown-menu">
					<cfif scholarships.RecordCount gt 0>
						<li><a href="?action=export&collection=scholarships" target="_new">Export</a></li>
						<!--- <cfif IsNumeric(client.scholarships.regionIDs)>
							<li><a href="/assets/calgrants/ui/printable/scholarships/scholarshipCertificate.cfm?Region_ID=#client.scholarships.regionIDs#" target="_new">Download Scholarship Certificates</a></li>
						<cfelse>
							<li><a href="##" onclick="alert('Filter on a single region to download scholarship certificates'); return false;">Download Scholarship Certificates</a></li>
						</cfif> --->
					<cfelse>
						<li><a href="##">None - no records available with filter settings</a></li>
					</cfif>
				</ul>
			</div>
			<span class="pull-right"><strong>Count:</strong> #scholarships.RecordCount#</span>
		</div>
	</div>
	
	<cfform name="scholarshipsForm" id="scholarshipsForm" action="#script_name#" method="post">
		<cfinput type="hidden" name="view" value="#view#">
			
		<div id="filter" class="alert alert-info alert-block" style="display: none;">
			<h4>Filters</h4>
			<table cellpadding="6">
				<tr valign="top">
					<td>
						<label>Cohort</label>
						<cfselect name="filterCohort" size="1" multiple="false" required="yes" message="Cohort filter is required" style="width: 150px;">
							<cfloop query="cohorts">
								<option value="#Cohort#"<cfif client.scholarships.cohort eq Cohort> selected</cfif>>#Cohort#</option>
							</cfloop>
						</cfselect>
					</td>
					<cfif IsUserInRole("Super User")>
						<td>
							<label>Regions</label>
							<cfselect name="filterRegionIDs" size="7" multiple="true" required="yes" message="Region filter is required" style="width: 150px;">
								<option value="All"<cfif client.scholarships.regionIDs eq "All"> selected</cfif>>All</option>
								<cfloop query="regions">
									<option value="#Region_ID#"<cfif ListFind(client.scholarships.regionIDs, Region_ID)> selected</cfif>>#Region_ID#</option>
								</cfloop>
							</cfselect>
						</td>
					</cfif>
					<td>
						<label>Organizations</label>
						<cfselect name="filterOrganizationIDs" size="7" multiple="true" required="yes" message="Organization filter is required" style="width: auto;">
							<option value="All"<cfif client.scholarships.organizationIDs eq "All"> selected</cfif>>All</option>
							<cfloop query="organizations">
							<option value="#Organization_ID#"<cfif ListFind(client.scholarships.organizationIDs, Organization_ID)> selected</cfif>>#Organization# - #City#</option>
							</cfloop>
						</cfselect>
					</td>
					<td>
						<label>Scholarship Types</label>
						<cfselect name="filterScholarshipTypes" size="7" multiple="true" required="yes" message="Scholarship Type is required" style="width: 150px;">
							<option value="All"<cfif client.scholarships.scholarshipTypes eq "All"> selected</cfif>>All</option>
							<option value="PBS"<cfif client.scholarships.scholarshipTypes eq "PBS"> selected</cfif>>PBS</option>
							<option value="Non-PBS"<cfif client.scholarships.scholarshipTypes eq "Non-PBS"> selected</cfif>>Non-PBS</option>
							<cfloop query="scholarshipTypes">
								<option value="#Scholarship_Type#"<cfif ListFind(client.scholarships.scholarshipTypes, Scholarship_Type)> selected</cfif>>#Scholarship_Type#</option>
							</cfloop>
						</cfselect>
					</td>
					<td>
						<label>Claim Status</label>
						<cfselect name="filterClaimStatus" size="1" multiple="false" required="yes" message="Claim Status filter is required" style="width: 150px;">
							<option value="All"<cfif client.scholarships.claimStatus eq "All"> selected</cfif>>All</option>
							<option value="Claimed"<cfif client.scholarships.claimStatus eq "Claimed"> selected</cfif>>Claimed</option>
							<option value="Unclaimed"<cfif client.scholarships.claimStatus eq "Unclaimed"> selected</cfif>>Unclaimed</option>
							<option value="Partial"<cfif client.scholarships.claimStatus eq "Partial"> selected</cfif>>Partial</option>
						</cfselect>
					</td>
				</tr>
				<tr>
					<td colspan="5">
						<button type="submit" class="btn btn-info">Apply</button> <a href="#script_name#?view=scholarships&resetFilters=true" class="btn btn-info">Clear</a>
					</td>
				</tr>
			</table>
		</div>

		<cfif scholarships.RecordCount gt 0>
			
			<script type="text/javascript">
			<!--
				var queryParams = #SerializeJSON(queryParams)#;
				/*
				var scholarship = kendo.data.Model.define({
					id: "scholarship_id",
					fields: {
						// uneditable fields
						scholarship_id: {type: "number", editable: false, nullable: true},
						student_id: {type: "number", editable: false, nullable: true},
						payment_schedule_id: {type: "number", editable: false, nullable: true},
						opt_out: {type: "boolean", editable: true, nullable: true},
						opt_out_reason: {type: "string", editable: true, nullable: true},
						institution1_id: {type: "number", editable: false, nullable: true},
						// editable cells
						institution1_document_date: {type: "date", editable: true, nullable: true},
						institution1_enrollment_units: {type: "number", editable: true, nullable: true},
						institution1_enrollment_attendance_level: {type: "string", editable: true, nullable: true},
						institution1_enrollment_degree_level: {type: "string", editable: true, nullable: true},
						institution1_performance_credits: {type: "number", editable: true, nullable: true},
						institution1_performance_gpa: {type: "number", editable: true, nullable: true},
						
						institution2_id: {type: "number", editable: false, nullable: true},
						institution2_document_date: {type: "date", editable: true, nullable: true},
						institution2_enrollment_units: {type: "number", editable: true, nullable: true},
						institution2_enrollment_attendance_level: {type: "string", editable: true, nullable: true},
						institution2_enrollment_degree_level: {type: "string", editable: true, nullable: true},
						institution2_performance_credits: {type: "number", editable: true, nullable: true},
						institution2_performance_gpa: {type: "number", editable: true, nullable: true},
						institution3_id: {type: "number", editable: false, nullable: true},
						institution3_document_date: {type: "date", editable: true, nullable: true},
						institution3_enrollment_units: {type: "number", editable: true, nullable: true},
						institution3_enrollment_attendance_level: {type: "string", editable: true, nullable: true},
						institution3_enrollment_degree_level: {type: "string", editable: true, nullable: true},
						institution3_performance_credits: {type: "number", editable: true, nullable: true},
						institution3_performance_gpa: {type: "number", editable: true, nullable: true},
						
						approval_date: {type: "date", editable: true, nullable: true},
						payment_submitted_date: {type: "date", editable: true, nullable: true},
						payment_date: {type: "date", editable: true, nullable: true},
						payment_type: {type: "string", editable: true, nullable: true},
						payment_amount: {type: "number", editable: true, nullable: true},
						payment_reference: {type: "string", editable: true, nullable: true},
						notes: {type: "string", editable: true, nullable: true},
						date_created: {type: "date", editable: false, nullable: true},
						// non-payment properties
						// scholarship
						claim_id: {type: "string", editable: false, nullable: true},
						first_name: { type: "string", editable: false, nullable: true},
						last_name: {type: "string", editable: false, nullable: true},
						full_name: {type: "string", editable: false, nullable: true},
						authorized: {type: "boolean", editable: false, nullable: true},
						// payment_schedule
						cohort: {type: "number", editable: false, nullable: true},
						scholarship_type: {type: "string", editable: false, nullable: true},
				
						term: {type: "string", editable: false, nullable: true},
						term_type: {type: "string", editable: false, nullable: true},
						verification_type: {type: "string", editable: false, nullable: true}
						// institution1
						
						// institution2
					}
				});
				*/
				var formatPhone = function(ph) {
					var ac = ph.substring(0, 3);
					var pre = ph.substring(3, 6);
					var num = ph.substring(6);
					return kendo.format("{0}-{1}-{2}", ac, pre, num);	
				}
				var scholarships = new kendo.data.DataSource({
					autoSync: false,
					transport: {
						read: {url: "/assets/calgrants/com/API.cfc", dataType: "json", type: "GET", cache: false},
						parameterMap: function(params, transportType) {
							params.objType = "scholarship";
							params.method = transportType;
							if (params.method == "read") {
								$.extend(params, queryParams);
							} else {
								$.extend(params, params.models[0]);
								params.models = "";
							}
							return params;
						}	
					},
					schema: {
						type: "json",
						//model: scholarship
					},
					batch: true,
					serverPaging: false,
					page: 1,
					pageSize: 100,
					serverSorting: false
				});
				var createGrid = function(){
					grid = $("##scholarshipsGrid").kendoGrid({
						dataSource: scholarships,
						autoBind: true,
						columns: [
							{field: "scholarship_id", title: "ID", template: "<a href='?view=editScholarship&Scholarship_ID=##=scholarship_id##'>##=scholarship_id##</a>", menu: false, width: 50},
							{field: "organization", title: "Organization", hidden: false, attributes: {"nowrap": "nowrap"}},
							{field: "site", title: "Workshop", template: "##=site## - ##=workshop_date##", hidden: false, attributes: {"nowrap": "nowrap"}},
							{field: "region_id", title: "Region", width: 80},
							{field: "cohort", title: "Cohort", width: 80},
							{field: "claim_id", title: "Claim ID", width: 120},
							{field: "full_name", title: "Name", attributes: {"nowrap": "nowrap"}},
							//{field: "phone1", title: "Phone 1", template: '##= (phone1) ? formatPhone(phone1) : "" ##', hidden: function(dataItem) {return dataItem.claim_date.length == 0 ? true : false}, attributes: {"nowrap": "nowrap"}},
							//{field: "phone2", title: "Phone 2", template: '##= (phone2) ? formatPhone(phone2) : "" ##', hidden: function(dataItem) {return dataItem.claim_date.length == 0 ? true : false}, attributes: {"nowrap": "nowrap"}},
							{field: "phone1", title: "Phone 1", template: '##= (phone1) ? phone1 : "" ##', hidden: function(dataItem) {return dataItem.claim_date.length == 0 ? true : false}, attributes: {"nowrap": "nowrap"}},
							{field: "phone2", title: "Phone 2", template: '##= (phone2) ? phone2 : "" ##', hidden: function(dataItem) {return dataItem.claim_date.length == 0 ? true : false}, attributes: {"nowrap": "nowrap"}},
							{field: "email", title: "E-mail", hidden: function(dataItem) {return dataItem.claim_date.length == 0 ? true : false}, attributes: {"nowrap": "nowrap"}},
							//{field: "gds_phone", title: "Phone", template: '##= (gds_phone) ? formatPhone(gds_phone) : "" ##', hidden: false, attributes: {"nowrap": "nowrap"}},
							{field: "gds_phone", title: "Phone", template: '##= (gds_phone) ? gds_phone : "" ##', hidden: false, attributes: {"nowrap": "nowrap"}},
							{field: "gds_email", title: "E-mail", hidden: false, attributes: {"nowrap": "nowrap"}},
							{field: "scholarship_type", title: "Scholarship Type", width: 140, template: function(dataItem) {
								if (dataItem.scholarship_type == "Performance Based Scholarship") {
									return "PBS";
								} else {
									return dataItem.scholarship_type;
								}
							}},
							{field: "claim_status", title: "Status", width: 110, template: function(dataItem) {
								if (dataItem.claim_status.split(";")[0] == "Partial") {
									var desc = (dataItem.claim_status.split(";")[1])?dataItem.claim_status.split(";")[1].toString().replace(/,/g, ", "):"Unknown";
									return "<abbr title='Missing " + desc + "'>" + dataItem.claim_status.split(";")[0] + "</abbr>"
								} else if (dataItem.claim_status.split(";")[0] == "Claimed") {
									return "<abbr title='" + dataItem.claim_date + "'>" + dataItem.claim_status.split(";")[0] + "</abbr>"
								} else {
									return dataItem.claim_status;
								}
							}}
						],
						editable: false,
						sortable: true,
						filterable: {
							extra: true,
							messages: {
								and: "and",
								or: "or",
								filter: "Apply",
								clear: "Clear",
								info: "Column filter",
								isFalse: "Is false",
								isTrue: "Is true",
								selectValue: "Select..."
							},
							operators: {
								string: {
									eq: "Equals",
									neq: "Does not equal",
									contains: "Contains",
									doesnotcontain: "Does not contain",
									startswith: "Starts with",
									endswith: "Ends with"
								},
								date: {
									eq: "On",
									neq: "Not on",
									gte: "On or after",
									gt: "After",
									lte: "On or before",
									lt: "Before"
								},
								number: {
									eq: "Equal",
									neq: "Not equal",
									gte: "Greater than or equal",
									gt: "Greater than",
									lte: "Less than or equal",
									lt: "Less than"
								}
							}
						},
						groupable: {
							messages: {
								empty: "Drop column here to group"		
							}
						},
						columnMenu: true,
						reorderable: true,
						resizable: true,
						scrollable: true,
						pageable: {
							pageSize: 20,
							pageSizes: [20, 50, 100, 200, 500],
							buttonCount: 20,
							input: true,
							info: true,
							messages: {
								display: "{0} - {1} of {2} records",
								empty: "Loading...",
								itemsPerPage: "records per page"
							}
						},
						dataBound: function(e) {
							$("##loadingContainer").hide();
							$("##scholarshipsGrid").show();
						}
					}).data("kendoGrid");
				};
				$(function() {
					createGrid();
				});
			//-->
			</script>
	
			<div id="loadingContainer" class="row-fluid">
				<div class="span4"></div>
				<div class="span4">
					<p>Data is loading...</p>
					<div class="progress progress-striped active">
						<div class="bar" style="width: 100%;"></div>
					</div>
				</div>
				<div class="span4"></div>
			</div>
			<div id="scholarshipsGrid" style="display: none;"></div>
			
		<cfelse>
		
			<div class="alert alert-info notFound">No scholarships</div>
	
			<script type="text/javascript" language="javascript">
			<!--
				$(function() {
					$("##filter").show();
				});
			// -->
			</script>
			
		</cfif>

	</cfform>
	
</cfoutput>
